package com.meng.mini.spring.beans;

import com.meng.mini.spring.beans.SingletonBeanRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例 bean 注册 实现
 * @author Meng Xu
 * @version 1.0.0
 * @date 2024-02-18 14:02
 **/
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    /**
     * bean name list
     */
    protected List<String> beanNames = new ArrayList<String>();

    /**
     * 存放所有单例bean map
     */
    protected Map<String,Object> singletons = new ConcurrentHashMap<String,Object>(256);

    /**
     * 装载 单例bean
     * @param beanName bean name
     * @param singletonObject 单例对象
     */
    @Override
    public void registerSingleton(String beanName, Object singletonObject) {
        //synchronized 保证注册bean始终为单例
        synchronized (this.singletons) {
            //放入map容器
            this.singletons.put(beanName,singletonObject);
            //names 放入
            this.beanNames.add(beanName);
        }

    }

    /**
     * 根据 bean名称获取单例对象
     * @param beanName bean name
     * @return singleton obj
     */
    @Override
    public Object getSingleton(String beanName) {
        return this.singletons.get(beanName);
    }

    /**
     * 判断当前bean是否为单例
     * @param beanName bean name
     * @return true or false
     */
    @Override
    public boolean containsSingleton(String beanName) {
        return this.singletons.containsKey(beanName);
    }

    /**
     * 获取所有单例beanNames
     * @return 那么集合
     */
    @Override
    public String[] getSingletonNames() {
        return (String[]) this.beanNames.toArray();
    }


    /**
     * 删除单例 obj
     * @param beanName bean name
     */
    protected void removeSingleton(String beanName){
        synchronized (this.singletons){
            this.beanNames.remove(beanName);
            this.singletons.remove(beanName);
        }
    }
}
